package br.com.remedioCerto.utis;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import br.com.remedioCerto.enumerator.SemanaEnum;

public class SemanaDialog extends DialogFragment {

	private String[] itens;
	private boolean[] itensEstado;
	private List<String> selecionados;


	public static SemanaDialog getInstance(boolean[] itensEstado){
		SemanaDialog dialog = new SemanaDialog();
		Bundle args = new Bundle();
		args.putBooleanArray("itensEstado", itensEstado);
		dialog.setArguments(args);
		return dialog;
	}
	
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
	    itens = SemanaEnum.getArray();
	    itensEstado = getArguments().getBooleanArray("itensEstado");
	    selecionados = new ArrayList<String>();
	    
	    for(int i=0; i<itens.length; i++){
	    	if(itensEstado[i]){
	    		selecionados.add(itens[i]);
	    	}
	    }
	    
	   
	    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	    builder.setTitle("Dias da Semana");
	    builder.setMultiChoiceItems(itens , itensEstado, onMultiChoiceClickListener);
	    builder.setNeutralButton("OK", neutralListener);
	    
	    return builder.create();
	}
	
	
	 private OnMultiChoiceClickListener onMultiChoiceClickListener = new DialogInterface.OnMultiChoiceClickListener(){
		  @Override
          public void onClick(DialogInterface dialog, int position, boolean isChecked) {
             
	   		   if (isChecked) {
	   			   selecionados.add(itens[position]);
	           }else if (selecionados.contains(itens[position])) {
	        	   selecionados.remove(itens[position]);
	           }
          }
	 };
	
	
	private  OnClickListener neutralListener = new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int id) {
        	 CallBackSemanaDialog callBack = (CallBackSemanaDialog) getActivity();
        	 callBack.retornoSemanaDialog(selecionados);
         }
     };
     

    public interface CallBackSemanaDialog{
    	 public void retornoSemanaDialog(List<String> selecionados);
     }
     
}
